<?php
namespace app\api\controller\v1;

use app\common\model\Area;
use app\common\model\LitestoreShopcategory;
use app\common\model\UserComplaint;
use app\common\service\LitestoreShop;
use app\common\service\Proxylog as ProxylogService;
use app\common\service\UserBank as UserBankService;
use app\common\service\UserCollectShop;
use think\Controller;
use think\Db;
use \app\common\service\User as UserService;
use \app\common\model\User as UserModel;
use think\Validate;

class Member extends Base {

    protected $noNeedLogin = ['index','getUserInfo','getaboutus'];
    protected $noNeedRight = '*';
    public $uid;
    public function __construct()
    {
        parent::__construct();
//        $userinfo = $this->userinfo;
        if (!$this->auth->match($this->noNeedLogin)) {
            $userinfo=$this->auth->getUser();
            $this->uid=$userinfo->id;
        }

    }

    public function index(){
        echo 'index';
    }
    /**注册的时候更新token , 且删除原来的token
     * @param $data
     * @param $uid
     * @return \app\common\model\User
     */
    public static function updateUserByToken($data,$uid){
        $map = ['id'=>$uid];
        $UserService = new UserService();
        $userinfo = $UserService->find($map);
        if(!empty($userinfo['token'])){
             \app\common\library\Token::delete($userinfo['token']);
        }
       return \app\common\model\User::update($data,['id'=>$uid]);
    }

    /**
     * 会员中心
     */
    public function MyCenter(){
        //余额
    }

    /**
     * 余额
     */
    public function  Mybalance(){

    }
    public function getCode1(){
        $userinfo=$this->auth->getUser();
//        $userinfo = $this->userinfo;
        $code = UserModel::where('id',$userinfo->id)->find();
        $data = ['code'=>$code->code,'pid'=>$code->id];
        if($code){
            $this->success("请求成功",$data);
        }else{
            $this->error("获取邀请码失败");
        }
    }
    /**
     *  获取邀请码
     */
    public function mycode() {
//        $userinfo = $this->userinfo;
        $userinfo = $this->auth->getUser();
        $UserModel = UserModel::where('id',$userinfo['id'])->find();
        $code = $UserModel['code'];
        if (!$code) {
            $code = $this->getcode($userinfo['id']);
            $UserModel = new UserModel();
            $res = $UserModel->save(['code'=>$code],['id'=>$userinfo['id']]);
            if ($res) {
                $this->success('邀请码生成成功',['code'=>$code,'uid'=>$userinfo['id']]);
            } else {
                $this->error( '邀请码生成失败！');
            }
        }else{
            $this->success('邀请码生成成功',['code'=>$code,'uid'=>$userinfo['id']]);
        }
    }
    private function getcode($uid) {
        $code = initcode();
        if ($this->recode($code)) {
            return $code;
        } else {
            while(true) {
                $this->getcode($uid);
            }
        }
    }

    private function recode($code) {
        if (UserModel::where('code',$code)->find()) {
            return false;
        }
        return true;
    }

    /**
     * 修改个人信息
     */
    public function updateMyInfo(){

        $post = $this->request->request('rows');
        if(!$post){
            $datas = json_encode((object)null);
            $this->error("传参格式有误",$datas,0);
        }
        $params = json_decode($post,true);

        if($params){
            $uid = $this->uid;
            $UserService = new UserService();
            $name = $params["name"];
            $res = $UserService->upMyInfo($name,$uid);
            if ($res) {
                $this->success('修改成功');
            } else {
                $this->error( '修改失败！');
            }
        }else{
            $this->error( '修改失败！');
        }
    }

    /**
     *  获取关于我们
     */
    public function getAbout(){
        $this->success('请求成功',['content'=>'关于我们']);
    }
    /**
     *  建议反馈
     */
    public function getAdvice(){

    }
    /**
     * 开通申请商家
     */
    public function registerStoreShop(){

        $post = $this->request->request('rows');
        if(!$post){
            $datas = json_encode((object)null);
            $this->error("传参格式有误",$datas,0);
        }

        $longitude= $this->request->request('longitude'); //经度114.03289881
        $latitude = $this->request->request('latitude'); //纬度 22.64382712

        $params = json_decode($post,true);
        $map['user_id']=  $this->uid;
        $params['user_id']=  $this->uid;
        if(isset($params['id'])&&!empty($params['id'])){
            $save_where=1;
        }else{
            $save_where=0;
        }
        if(!empty($longitude)&&!empty($latitude)){
            $params['longitude']=$longitude;
            $params['latitude']=$latitude;
            $params['location']=$longitude.','.$latitude;
        }else{
            if( cookie( 'cache_ip_location' )){
                if(!empty(cookie( 'cache_ip_location' )['content'])){
                    $point=cookie( 'cache_ip_location' )['content']['point'];
                    $params['longitude']=$point['x'];
                    $params['latitude']=$point['y'];
                    $params['location']=$point['x'].','.$point['y'];
                }
            }
        }


        $LitestoreShop = new LitestoreShop();

        $result =$LitestoreShop->registerShop($map,$params,$save_where);

        if($result){


            $this->success($result['msg'],$result['data'],$result['code']);
        }else{
            $this->error($result['msg'],$result['data']);
        }
    }

    /**
     * 关于我们接口
     */
    public function getaboutus(){
       try{
           $site=\think\Config::get('site');
           $aboutus=$site['aboutus'];
           if(empty($aboutus)){
               return json(array('code'=>0,"data"=>[],'msg'=>"暂无请求数据"));
           }
       }catch (\Exception $e){
           return json(array('code'=>0,"data"=>[],'msg'=>"暂无请求数据"));
       }
        $aboutus = str_ireplace("/uploads",url('/','',true,true).'uploads',$aboutus);//用"你好"替换字符串中的"hello"
        $data['content']=$aboutus;
        $this->success('请求成功',$data);

    }

    /**
     * 获取加入vip会员图片
     */
    public function joinvip(){

        try{
            $site=\think\Config::get('site');
            $vip_info=$site['vip_info'];
            if(empty($vip_info)){
                return json(array('code'=>0,"data"=>[],'msg'=>"暂无请求数据"));
            }
        }catch (\Exception $e){
            return json(array('code'=>0,"data"=>[],'msg'=>"暂无请求数据"));
        }
        $data['img']=$vip_info;
        $this->success('获取成功',$data);
    }

    /**
     * 开通vip模拟
     */
    public function addjoinvip(){
        $model_user = new \app\common\model\User();
        $user=$model_user->where(['id'=>$this->uid])->field('is_shop,is_vip,is_agent,server_type,id')->find()->toArray();
        try{
            $res = $model_user->join_vip($this->uid);
            if(!$res){
                $this->error('已开通过vip会员',$user);
            }
        }catch (\Exception $e){
            $this->error('操作失败，请重试',$user);
        }


        $this->success('模拟：开通成功',$user);
    }



    /**
     * 获取用户商铺信息
     */
    public function getShop(){
        $userinfo = $this->userinfo;
        $uid = $userinfo['id'];
        $shopMedel=new \app\common\model\LitestoreShop();
        $shopList=$shopMedel::get(['user_id'=>$uid]);
        if(!empty($shopList)){
            $shopList=$shopList->toArray();
            $shopCategory=new LitestoreShopcategory();
            $AreaList=new Area();
            $shopCategoryOne=$shopCategory->where(['id'=>array('eq',$shopList['category_id'])])->find();
            $provinceOne=$AreaList->where(['id'=>$shopList['province']])->find();
            $cityOne=$AreaList->where(['id'=>$shopList['city']])->find();
            $areaOne=$AreaList->where(['id'=>$shopList['area']])->find();
            $shopList['category_name']=$shopCategoryOne->name;

            if(!empty($provinceOne)){
                $shopList['province_name']=$provinceOne->name;
            }
            if(!empty($cityOne)){
                $shopList['city_name']=$cityOne->name;
            }
            if(!empty($areaOne)){
                $shopList['area_name']=$areaOne->name;
            }
            $shopList['category_name']=$shopCategoryOne->name;
        }else{
            return json(array('code'=>0,"data"=>[],'msg'=>"暂无请求数据"));
        }
        $this->success("请求成功",$shopList);

    }


    /**
     * 检查店铺是否被收藏
     *
     */
    public function getCheckShop(){
            $user=$this->auth->getUser();

            $id = $this->request->request('id');
            $UserCollectShop = new \app\common\model\UserCollectShop();
            $count=$UserCollectShop->where(['shop_id'=>array('eq',$id),'user_id'=>array('eq',$user->id)])->count();
            if(!empty($count)){
                $this->success('已经收藏',[],1);
            }else{
                $this->success('未收藏',[],0);
            }


    }

    /**
     * 我的邀请列表
     */
    public function getMyCodeList(){
        $userinfo = $this->userinfo;
        $uid = $userinfo['id'];
        //页码
        $live = $this->request->request('live');
        $offset = $this->request->request('offset');
        $offsets = $offset?$offset:1;
        //加载条数默认10条
        $number = $this->request->request('limit');
        $limit = $number?$number:10;
        $UserService = new UserService();
       $code = $UserService->myCodeListService($live,$uid,$limit,$offsets);

      if($code){
          $data = collection($code)->toArray();
          $this->success("请求成功",$data);
      }else{
          return json(array('code'=>0,"data"=>[],'msg'=>"暂无请求数据"));
      }
    }

    /**
     * 我的邀请列表--新增
     */
    public function getMyCodeListNew(){

        $model_user = new UserModel();
        $live= $this->request->request('live');
        $parent_user_id= $this->request->request('parent_user_id');
        $page=$this->request->request('offset');
        $number = $this->request->request('limit');
        $limit = $number?$number:10;
        $user=$this->auth->getUser();
        $uid=$user->id;
        if($live==1){
            $data=$model_user->myteamusersnews($live,$uid,$page,$limit);
        }elseif ($live==2){
            $data=$model_user->myteamusersnews($live,$parent_user_id,$page,$limit);
        }else{
            $data=[];
        }
        if(empty($data['data'])){
            $this->error("暂无请求数据",$data);
        }else{
            $this->success('请求成功',$data);
        }


    }

    /**
     * 添加银行卡
     */
    public function createMyBank(){
        $post = $this->request->request('rows');
        if(!$post){
            $datas = json_encode((object)null);
            $this->error("传参格式有误",$datas,0);
        }
        $params = json_decode($post,true);
        $UserBankService = new UserBankService();
        $map['user_id'] = $this->uid;
        $params['user_id'] = $this->uid;
        $map['account'] = $params['account'];
        $result = $UserBankService->bindUserBank($map,$params);
        //手机验证码验证
        if($result['code']){
            $data = $this->nullcode;
            $this->success($result['msg'],$data,$result['code']);
        }else{
            $this->error($result['msg']);
        }
    }

    /**
     * 银行卡列表
     */
    public function myBankList(){
        $UserBankService = new UserBankService();
        $map['user_id']=  $this->uid;
        $order = "createtime desc";
        $offset = $this->request->request('offset');
        $offsets = $offset?$offset:0;
        $number = $this->request->request('limit');
        $limit = $number?$number:6;
        $limits = $offsets.','.$limit;
        $field = "id,account,banking_id";
        $result = $UserBankService->select($map,$field,$order,$limits);
        foreach($result as &$v){

            $v['account'] = formatBankCardNo($v['account']);
            $v['bankname']=getBrankName($v['banking_id']);
            $v['banktype'] = "储蓄卡";
        }
        if($result){
            $this->success('success',$result);
        }else{
            $data = $this->nullcode;
            $this->error('暂无银行卡',$data);
        }
    }

    /**
     * 加入代理
     */
    public function joinProxy(){
        $post = $this->request->request('rows');
        if(!$post){
            $datas = json_encode((object)null);
            $this->error("传参格式有误",$datas,0);
        }
        $params = json_decode($post,true);

        if(isset($params['price'])&&empty($params['price'])){
            $this->error("您申请的价格待定，提交之后由客服人员联系您！",[],0);
        }

        $user=$this->auth->getUser();
        $ProxylogService = new ProxylogService();
        $uid = $user['id'];
        $map['user_id'] = $uid;
        $params['user_id']=$uid;
        $result = $ProxylogService->joinProxyService($map,$params);

        if($result['code']){
            $data = $this->nullcode;
            $this->success($result['msg'],$data,$result['code']);
        }else{
            $this->error('申请失败');
        }
    }

    /**
     * 加入代理
     */
    public function IsProxy(){
        $params['is_agent']=$this->request->request('is_agent');
        $params['server_type']=$this->request->request('server_type');
        $params['province']=$this->request->request('province');
        $params['city']=$this->request->request('city');
        $params['area']=$this->request->request('area');
        $params['price']=$this->request->request('price');
        $params['regione']=$this->request->request('regione');


        if(isset($params['price'])&&empty($params['price'])){
            $this->error("您申请的价格待定，提交之后由客服人员联系您！",[],0);
        }

        $user=$this->auth->getUser();
        $ProxylogService = new ProxylogService();
        $uid = $user['id'];
        $map['user_id'] = $uid;
        $params['user_id']=$uid;
        $result = $ProxylogService->IsjoinProxyService($map,$params);

        if($result['code']==1){
            $data = $this->nullcode;
            $this->success($result['msg'],$data,$result['code']);
        }else{
            $this->error('不可申请');
        }
    }

    public function myCollectStore(){
    $offset = $this->request->request('offset');
    $offsets = $offset?$offset:1;
    $number = $this->request->request('limit');
    $longitude= $this->request->request('longitude'); //经度114.03289881
    $latitude = $this->request->request('latitude'); //纬度 22.64382712
    $limit = $number?$number:10;
        $x=114.045094;//经度
        $y=22.646479;//维度

    //经度
    if($latitude>0&&$latitude>0){
        $x=trim($longitude);
        $y=trim($latitude);
        $cityList=getCityList($y.','.$x);
        if(!empty($cityList)){
            $city=Db::name('area')->where(['name'=>$cityList['city']])->find();
            $map['city'] = $city['id'];
        }
    }else{
        if( cookie( 'cache_ip_location' )){
            if(!empty(cookie( 'cache_ip_location' )['content'])){
                $point=cookie( 'cache_ip_location' )['content']['point'];
                $x=$point['x'];
                $y=$point['y'];
            }
        }
        if(cookie('cache_location_city')){
            $area=cookie('cache_location_city');
            $city=get_location_city($area['city']);
            $map['city'] = $city['id'];
        }

    }
//    $limits = $offsets.','.$limit;
    $UserCollectShop = new UserCollectShop();
    $uid = $this->uid;

    $result =$UserCollectShop->collectStore($uid,$limit,$offsets);

    if(!$result){
        return json(array('code'=>0,"data"=>[],'msg'=>"暂无收藏数据"));
     }

    foreach ($result as $key=>$val){
        if(!empty($x)&!empty($y)){
            if(!empty($val['longitude'])){

                $result[$key]['length'] = web_getDistance($x,$y,$val['longitude'],$val['latitude']);
            }else{
                $result[$key]['length']=0;
            }

        }else{
            $result[$key]['length']=0;
        }
        if(isset($val['get_shop_by_tag'])){
            $result[$key]['tag_list']=$val['get_shop_by_tag'];
        }
    }

        $this->success('success',$result);
    }
    public function getTokenInfo(){
        halt($this->uid);
    }

    /**
     * 获取用户详情
     */
    public function getMyInfo(){
       $userinfo = $this->userinfo;

        $this->success('success',$userinfo);
    }

    /**
     * 用户的二维码
     */
    public function getMyCreateCode(){
        $userinfo = $this->userinfo;
        $code = $userinfo['code'];
        if(!$code){
            $this->error('暂时没有设置验证码');
        }
       $UserService =  new UserService();
       $result =  $UserService->createcode($code);
       $data = [
           'qr_code'=>$result,
           'code'=>$code,
           'url'=>url('/index/index/index',array('code'=>$code),true,true)
       ];
        $this->success('success',$data);
    }

    public function complaint(){
        $UserComplaint=new UserComplaint();
        $uid = $this->uid;

        $phone = $this->request->request('phone');
        $content = $this->request->request('content');
        $rule = [
            'content'  => 'require|length:1,200',
        ];
        $msg = [
            'content.require'  => '内容不能为空',
            'content.length'  => '内容长度必须为1到200位',
        ];
        $data = [
            'content'   => $content,
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($data);
        if (!$result) {
            $this->error(__($validate->getError()));
        }else{

            $data['user_id']=$uid;
            $data['phone']=$phone;
            $data['createtime']=time();
            $res=$UserComplaint->insertGetId($data);
            if(!$res){
                $this->error('提交失败');
            }
        }

        $this->success('提交成功');

    }


}